"""
用户数据库模型
"""
from typing import Dict
import enum
from tortoise import fields, Model
from ..core.security import create_access_token


class UserStatus(enum.Enum):
    """用户状态枚举类"""
    ACTIVE = "1"
    INACTIVE = "0"


class User(Model):
    """用户表"""
    job_number = fields.CharField(pk=True, generated=False, max_length=50, index=True, description="工号")
    username = fields.CharField(max_length=50, index=True, description="用户名")
    password = fields.CharField(max_length=128, description="密码")
    # 岗位
    # post = fields.CharField(max_length=50, description="岗位")
    # 与角色的外键关系，会自动创建 role_id 字段,role_id 是一个字符类型的，可以为空
    role = fields.ForeignKeyField('models.Role', related_name='users', description="角色")
    phone_number = fields.CharField(max_length=11, description="手机号", null=True)
    email = fields.CharField(max_length=50, description="邮箱", null=True)
    status = fields.CharEnumField(enum_type=UserStatus, default=UserStatus.ACTIVE, description="用户状态")
    created_at = fields.DatetimeField(auto_now_add=True, description="创建时间")
    updated_at = fields.DatetimeField(auto_now=True, description="更新时间")

    class Meta(Model.Meta):
        table = "userinfo"
        description = "用户表"
        ordering = ["created_at"]  # 按照创建时间升序排序

    def generate_token(self) -> str:
        """
        为用户生成JWT token
        Returns:
            str: JWT token
        """
        token_data = {
            "username": self.username,
            "job_number": self.job_number,
            "role_id": getattr(self, 'role_id', None)  # role_id现在可为空
        }
        return create_access_token(data=token_data)

    def to_dict_with_token(self) -> Dict:
        """
        返回包含token的用户信息字典
        Returns:
            dict: 用户信息和token
        """
        return {
            "username": self.username,
            "job_number": self.job_number,
            "role_id": getattr(self, 'role_id', None),  # role_id现在可为空
            "accessToken": self.generate_token(),
            "status": self.status.value,
            "phone_number": self.phone_number,
            "email": self.email
        }

    def __str__(self):
        return f"User username={self.username}, job_number={self.job_number})"

